#  Copyright 2009-2010 Michal Trzcinka
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
# 
#  http://www.apache.org/licenses/LICENSE-2.0
# 
#  Unless required by applicable law or agreed to in writing, software distributed
#  under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
#  CONDITIONS OF ANY KIND, either express or implied. See the License for the
#  specific language governing permissions and limitations under the License.

if $0 != 'irb' #don't want to run it in console

  require 'rufus/scheduler'
  scheduler = Rufus::Scheduler.start_new
  
  scheduler.every("1m") do
    puts "[SCHEDULER] Executing scheduled tasks..."
    start = Time.now
    #Destroying all grid events that weren't received
    GridEvent.find(:all, :conditions => ["created_at < ?", 2.minutes.ago]).each do |event|
      event.destroy
    end

    #Destroying all stale sessions and logging out corresponding users
    ActiveRecord::SessionStore::Session.find(:all, :conditions => ['updated_at < ?', 12.hours.ago.utc]).each do |session|
      User.transaction do
        User.find(session.data[:user_id]).logout if session.data[:user_id]
        session.destroy
      end
    end
    puts "[SCHEDULER] Scheduled task completed in #{Time.now - start} s"
  end  
  
end

